<?php


namespace app\controller\v1;

use app\controller\CommonController;
use app\model\v1\Image as ImageModel;
use app\service\v1\ManagerToken;
use app\validate\v1\Ids;
use app\validate\v1\PageLimit;
use app\validate\v1\PositiveInt;
use app\validate\v1\Status;
use app\validate\v1\Url;
use think\Request;

class Image extends CommonController
{
    /**
     * 图片列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DbException
     */
    public function getList(Request $request): \think\response\Json
    {
        $managerId = ManagerToken::getCurrentMID();
        $page = $request->post('page');
        $limit = $request->post('limit');
        $photoGroupId = $request->post('photo_group_id');
        $from = $request->post('from');

        validate(PageLimit::class)->check(['page' => $page, 'limit' => $limit]);
        if (!is_null($photoGroupId)) {
            validate(Ids::class)->scene('single')->check(['id' => $photoGroupId]);
        }
        if (!is_null($from)) {
            validate(Status::class)->check(['status' => $from]);
        }

        $imagePage = (new ImageModel)->getList($managerId, $page, $limit, $photoGroupId, $from);
        return $this->responsePage($imagePage);
    }

    /**
     * 图片添加
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function add(Request $request): \think\response\Json
    {
        $managerId = ManagerToken::getCurrentMID();
        $urls = explode(',', $request->post('urls'));
        $photoGroupId = (int)$request->post('photo_group_id');
        $from = (int)$request->post('from');

        validate(Ids::class)->scene('single')->check(['id' => $managerId]);
        validate(Url::class)->check(['urls' => $urls]);
        validate(PositiveInt::class)->check(['positiveInt' => $photoGroupId]);
        validate(Status::class)->check(['status' => $from]);

        $createData = (new ImageModel)->add($managerId, $urls, $photoGroupId, $from);
        return $this->responseData($createData);
    }
}